﻿using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsPipeServer
{
     class PipeServer
    {
        private  readonly NamedPipeServerStream m_pipe = new NamedPipeServerStream("Echo", PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous | PipeOptions.WriteThrough);

        public PipeServer()
        {
            m_pipe.BeginWaitForConnection(ClientConnected, null);
        }

        private void ClientConnected(IAsyncResult ar)
        {
            new PipeServer();
            m_pipe.EndWaitForConnection(ar);
            byte[] data = new byte[1000];
            m_pipe.BeginRead(data, 0, data.Length, GotRequest, data);
        }

        private void GotRequest(IAsyncResult ar)
        {
            int bytesRead = m_pipe.EndRead(ar);
            byte[] data = (Byte[])ar.AsyncState;
            data = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(data, 0, bytesRead).ToUpper().ToCharArray());
            m_pipe.BeginWrite(data, 0, data.Length, WriteDone, null);
        }

        private void WriteDone(IAsyncResult ar)
        {
            m_pipe.EndWrite(ar);
            m_pipe.Close();
        }
    }
}
